﻿using System.Text;

namespace mapshiftApplication.Helpers
{
    public class LogHelper
    {
        private static readonly object _lockObj = new object();
        private static readonly string _logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "logs");

        // 日志等级枚举
        public enum LogLevel
        {
            Info,
            Warning,
            Error,
            Debug
        }

        // 写日志（默认 Info）
        public static void Log(string message, LogLevel level = LogLevel.Info)
        {
            try
            {
                string date = DateTime.Now.ToString("yyyy-MM-dd");
                string logFile = Path.Combine(_logDirectory, $"{date}.log");

                // 日志格式： [时间] [等级] 消息
                string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{level}] {message}";

                lock (_lockObj)
                {
                    // 自动创建目录
                    if (!Directory.Exists(_logDirectory))
                    {
                        Directory.CreateDirectory(_logDirectory);
                    }

                    // 写入日志文件
                    File.AppendAllText(logFile, logEntry + Environment.NewLine, Encoding.UTF8);
                }
            }
            catch (Exception ex)
            {
                // 你也可以选择记录错误到事件日志或忽略
                Console.WriteLine($"写入日志失败: {ex.Message}");
            }
        }

        // 便捷方法
        public static void Info(string msg) => Log(msg, LogLevel.Info);
        public static void Warn(string msg) => Log(msg, LogLevel.Warning);
        public static void Error(string msg) => Log(msg, LogLevel.Error);
        public static void Debug(string msg) => Log(msg, LogLevel.Debug);
    }
}
